import { interpreter } from "@/api/request";
import { getHotQuestionList } from "@/api/zixun";
import { Tab } from "@/utils/cache";
import debounce from "@/utils/debounce";
import { computed, onMounted, ref } from "vue";

export interface Hot {
  id: number;
  content: string;
  robot_id: number;
  hot_index: number;
  created_at: string;
  updated_at: string;
}
export default function useHot() {
  const pagination = ref<{
    size: number;
    page: number;
    currentCase: number | null;
  }>({
    size: 3,
    page: 0,
    currentCase: null
  });
  const hot = ref<Record<string, Array<Hot>>>({});

  const getHotList = async (id: number) => {
    if (hot.value[id]) {
      pagination.value.page = 0;
      pagination.value.currentCase = id;
      return;
    }
    const [err, res] = await interpreter(getHotQuestionList(id));
    if (!err) {
      if (!hot.value[id]) {
        pagination.value.currentCase = id;
        hot.value[id] = res;
      }
    }
  };
  const currentHot = computed(() => {
    const { currentCase } = pagination.value;

    if (currentCase) {
      return hot.value[currentCase];
    }
    return [];
  });

  const getThree = computed(() => {
    if (currentHot.value.length < 3) {
      return currentHot.value;
    }
    const { size, page } = pagination.value;
    const list = currentHot.value.slice(page, size + page);
    if (list.length === 3) {
      return list;
    }
    const diff = currentHot.value.slice(0, 3 - list.length);
    return [...list, ...diff];
  });

  const changeHot = debounce(
    (caseType: number) => {
      const { page, size, currentCase } = pagination.value;
      if (caseType !== currentCase) {
        pagination.value.currentCase = caseType;
      }
      const currentLen = hot.value[caseType].length;
      if (currentLen <= 3) {
        uni.showToast({
          title: "没有更多了",
          icon: "none"
        });
        return;
      }
      if (currentLen) {
        pagination.value.page = (page + size) % currentLen;
      }
    },
    500,
    true
  );

  return {
    getThree,
    currentHot,
    getHotList,
    changeHot
  };
}
